import React, { Button, Form, Modal } from 'antd';
import './index.less';
import { Divider, Menu, Switch } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { request } from 'umi';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import EditCom from './auth';
import { PlusOutlined } from '@ant-design/icons';
export default (props: any) => {
  const [items, setItems] = useState([]);
  const [selectKey, setselectKey] = useState('');
  const editRef = useRef();
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm(); //搜索表单
  const getRoles = () => {
    request('/sys/role/roleList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      console.log(res);
      const rolelist = res?.data || [];
      rolelist.map((e: any, i: Number) => {
        rolelist[i]['label'] = e['roleName'];
        rolelist[i]['key'] = e['roleId'];
      });
      setselectKey(rolelist[0]['key']);
      setItems(rolelist);
    });
  };
  useEffect(() => {
    actionRef.current?.reload();
  }, [selectKey]);
  useEffect(() => {
    getRoles();
  }, []);
  const deleteFn = (id) => {
    Modal.confirm({
      title: '确认删除？',
      content: '',
      onOk() {
        console.log('OK');

        request('/sys/role/deleteRoleUser', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: {
            userId: id,
            roleId: selectKey,
          },
        }).then(() => {
          if (id == selectKey) {
            setselectKey('');
          }
          getRoles();
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const columns: ProColumns[] = [
    {
      title: '登录名称',
      align: 'center',
      key: 'loginName',
      dataIndex: 'loginName',
      hideInTable: true,
    },
    {
      title: '用户名',
      align: 'center',
      key: 'userName',
      dataIndex: 'userName',
    },
    {
      title: '系统登陆账号',
      align: 'center',
      key: 'loginName',
      dataIndex: 'loginName',
    },
    {
      title: '归属公司',
      align: 'center',
      key: 'companyName',
      dataIndex: 'companyName',
    },
    {
      title: '归属部门',
      align: 'center',
      key: 'departmentName',
      dataIndex: 'departmentName',
    },
    {
      title: '用户身份',
      align: 'center',
      key: 'userRoleTypeName',
      dataIndex: 'userRoleTypeName',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            editRef.current?.init(record.userId, record);
          }}
        >
          分配角色
        </a>,
        <a
          key="deleteable"
          onClick={() => {
            deleteFn(record.userId);
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  return (
    <div className="RolesContainer">
      <div className="rolesMenus">
        <Menu
          onClick={(e) => {
            setselectKey(e.key);
          }}
          selectedKeys={[selectKey]}
        >
          {items.map((item: any, i: number) => {
            return (
              <Menu.Item key={item.key}>
                <div>
                  <span style={{ marginLeft: '10px' }}>{item.label}</span>
                </div>
              </Menu.Item>
            );
          })}
        </Menu>
      </div>
      <div className="rolesContent">
        {
          selectKey && <ProTable
            actionRef={actionRef}
            columns={columns}
            // search={false}
            params={form.getFieldsValue()}
            // params 是需要自带的参数
            // 这个参数优先级更高，会覆盖查询表单的参数
            request={async (
              // 第一个参数 params 查询表单和 params 参数的结合
              // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
              params: T & {
                pageSize: number;
                current: number;
              },
              sort,
              filter,
            ) => {
              // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
              // 如果需要转化参数可以在这里进行修改
              console.log(params, sort, filter);
              const response: any = await request('/sys/account/userList', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                data: {
                  ...params,
                  ...{
                    pageNo: params.current,
                    pageSize: params.pageSize,
                    roleId: selectKey,
                  },
                },
              });
              return {
                data: response?.data?.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: response?.data?.totalCount,
              };
            }}
            toolBarRender={() => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  editRef.current?.init();
                }}
                type="primary"
              >
                新建
              </Button>,
            ]}
          />
        }

      </div>

      <EditCom
        ref={editRef}
        callback={() => {
          actionRef.current?.reload();
        }}
      />
    </div>
  );
};
